// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
import * as Fetch from '../../../../../../utils/request'
import { convertToHeaders } from "../../../../../../utils/request"
import CoreSiteFriendlyLink = API.CoreSiteFriendlyLink

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  if (process.env.NEXT_PUBLIC_RENFEID_ACTIVE == 'preview') {
    // 预览模式
    if (req.method === 'GET') {
      let cronJobs: CoreSiteFriendlyLink[] = []
      for (let i = 1; i < 10; i++) {
        cronJobs.push({
          sitename: `任霏博客演示-${i}`,
          sitelink: "https://www.renfei.net",
          contactName: "任霏",
          remarks: "好友",
          id: `${i}`,
          isDelete: false,
          addtime: "2022-09-03 18:42:29",
          auditPass: true,
          linkType: 1,
          contactEmail: "i@renfei.net",
          contactQq: "16076276",
          orderId: 0,
        })
      }
      res.status(200).json({
        code: 200,
        message: 'OK',
        timestamp: new Date().valueOf(),
        signature: '',
        nonce: '',
        data: cronJobs
      })
    } else {
      res.status(403).json({
        code: 403,
        message: '预览模式，仅支持查看，不支持数据修改。',
        timestamp: new Date().valueOf(),
        signature: '',
        nonce: ''
      })
    }
  } else {
    const token = req.cookies['accessToken']
    if (token) {
      let url = `/_/api/core/friendlylink`
      if (req.method === 'GET') {
        await Fetch.get(url, convertToHeaders(req.headers, req.socket.remoteAddress), token, true).then(result => {
          res.status(200).json(result)
        })
      } else if (req.method === 'POST') {
        await Fetch.post(url, req.body, convertToHeaders(req.headers, req.socket.remoteAddress), token, true).then(result => {
          res.status(200).json(result)
        })
      } else {
        res.status(405).json({
          code: 405,
          message: '不支持的请求方法。',
          timestamp: new Date().valueOf(),
          signature: '',
          nonce: ''
        })
      }
    } else {
      res.status(401).json({
        code: 401,
        message: '需要身份验证。',
        timestamp: new Date().valueOf(),
        signature: '',
        nonce: ''
      })
    }
  }
}

export default handler